//
//  LCImageViewController.m
//  BJS151148_ TeamProject_Travel
//
//  Created by lanou3g on 16/3/23.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "LCImageViewController.h"
#import "LCImageViewCell.h"

#import "CDHttpHelper.h"
#import "PersonalModel.h"
#import "LCCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "SDRefresh.h"
#import "LCEChatRoomVC.h"
@interface LCImageViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UICollectionView * aCollctionView;
@property(nonatomic,strong)SDRefreshFooterView * refreshFooter;
@property (nonatomic, weak) SDRefreshHeaderView *refreshHeader;
@property (nonatomic, assign) NSInteger totalRowCount;
@property(nonatomic,assign)NSInteger totalPicPage;
@property(nonatomic,strong)NSMutableArray * allPicArray;
@property(nonatomic,strong)NSIndexPath * index;
@end

@implementation LCImageViewController


-(NSMutableArray *)allDataArray
{
    if (!_allDataArray) {
        _allDataArray = [[NSMutableArray alloc]init];
    }
    return _allDataArray;
}

- (NSMutableArray *)allPicArray{
    if (!_allPicArray) {
        _allPicArray = [[NSMutableArray alloc]init];
    }
    return _allPicArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.allDataArray = [NSMutableArray array];
    
    self.aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.aView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.aView];
    self.aImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 70, 60, 60)];
    [self.aImageView sd_setImageWithURL:[NSURL URLWithString:self.model.user[@"image"]]];
    self.aImageView.layer.cornerRadius = 4;
    self.aImageView.layer.masksToBounds = YES;
    
    [self.aView addSubview:self.aImageView];
    self.aLbael = [[UILabel alloc]initWithFrame:CGRectMake(self.aImageView.frame.size.width+10, 75, self.view.frame.size.width - 200, 25)];
    self.aLbael.text = self.model.user[@"name"];
    [self.view addSubview:self.aLbael];

    self.bLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.aImageView.frame.size.width+10, self.aLbael.frame.size.height + 80, self.aLbael.frame.size.width - 50, 25)];
    [self.view addSubview:self.bLabel];
    self.aLbael.layer.cornerRadius = 4;
    self.aLbael.layer.masksToBounds = YES;
    self.bLabel.layer.cornerRadius = 4;
    self.bLabel.layer.masksToBounds = YES;
    
    
    self.aButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.aButton.frame = CGRectMake(5, self.aImageView.frame.size.height + 80, self.view.frame.size.width / 2 - 10, 30);
    [self.view addSubview:self.aButton];
    self.aButton.layer.cornerRadius = 4;
    self.aButton.layer.masksToBounds = YES;
    
    self.bButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.bButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 + 5, self.aImageView.frame.size.height + 80, self.aButton.frame.size.width, 30);
    [self.view addSubview:self.bButton];

    [self.aButton setTitle:@"关注" forState:(UIControlStateNormal)];
    [self.bButton setTitle:@"私信" forState:(UIControlStateNormal)];
    [self.bButton addTarget:self action:@selector(chat) forControlEvents:(UIControlEventTouchUpInside)];
    self.bButton.layer.cornerRadius = 4;
    self.bButton.layer.masksToBounds = YES;
    
    
    self.senderImageView = [[UIImageView alloc]initWithFrame:(CGRectMake(CGRectGetMaxX(self.aLbael.frame)+10, CGRectGetMinY(self.aLbael.frame), CGRectGetHeight(self.aLbael.frame), CGRectGetHeight(self.aLbael.frame)))];
    self.senderImageView.backgroundColor = [UIColor whiteColor];
    self.senderImageView.layer.cornerRadius = 12;
    self.senderImageView.layer.masksToBounds = YES;
    
   
    
  [self.view addSubview:self.senderImageView];
    
    
    
    self.segmentCon = [[UISegmentedControl alloc]initWithItems:@[@"游记",@"喜欢"]];
    self.segmentCon.frame = CGRectMake(5, self.bButton.frame.size.height + 150, self.view.frame.size.width - 10, 40);
    self.segmentCon.layer.cornerRadius = 4;
    self.segmentCon.layer.masksToBounds = YES;
    [self.segmentCon addTarget:self action:@selector(pushacTion) forControlEvents:(UIControlEventValueChanged)];
    
    self.aScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.segmentCon.frame), [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(self.segmentCon.frame))];
    self.aScrollView.backgroundColor = [UIColor whiteColor];
    self.aScrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * 2, CGRectGetHeight(self.aScrollView.frame));
    self.aScrollView.pagingEnabled = YES;
    self.aScrollView.bounces = NO;
    self.aScrollView.delegate = self;
    [self.view addSubview:self.aScrollView];

    
    [self.view addSubview:self.segmentCon];
    
    
    self.aTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0 , self.view.frame.size.width, self.view.frame.size.height -  CGRectGetMaxY(self.segmentCon.frame)) style:(UITableViewStyleGrouped)];
    
    [self.aScrollView addSubview:self.aTableView];
    self.aTableView.delegate = self;
    self.aTableView.dataSource =self;
    
    [self.aTableView registerNib:[UINib nibWithNibName:@"LCImageViewCell"  bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
  
    
    [self handleData];
    [self setupFooter];
    [self setupHeader];
    
    self.totalPicPage = 1;
    [self handleDataForPicWithPage:self.totalPicPage];
    [self updateData];
    
    
}

- (void)chat{
    LCEChatRoomVC *cdVC = [[LCEChatRoomVC alloc]init];
    [self.navigationController pushViewController:cdVC animated:YES];
}

- (void)setupHeader
{
    if (self.totalRowCount > 1) {
        self.totalRowCount -= 1;
    }else{
        self.totalRowCount = 1;
    }
    
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    // 默认是在navigationController环境下，如果不是在此环境下，请设置
    refreshHeader.isEffectedByNavigationController = NO;
    [refreshHeader addToScrollView:self.aTableView];
    
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    __weak typeof(self) weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.totalRowCount += 3;
            [weakSelf.aTableView reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
}

-(void)setupFooter
{
    self.refreshFooter = [SDRefreshFooterView refreshView];
    [self.refreshFooter addToScrollView:self.aTableView];
    [self.refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = self.refreshFooter;
    
}

- (void)footerRefresh
{
    self.totalRowCount +=1;
    
   [self handleData];
}

- (void)handleData
{

    
    [[CDHttpHelper defaultCDHttpHelper]get:[NSString stringWithFormat:@"https://chanyouji.com/api/users/%@.json?page=%ld",self.model.user[@"id"],self.totalRowCount]params:nil success:^(id responseObj) {
        NSError *error = nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:&error];
        
        // "游记"解析
        // 页面头部, 直接赋值
        self.image = dictionary[@"image"];
        self.gender = [dictionary[@"gender"] integerValue];
        self.trips_count = [dictionary[@"trips_count"] intValue];
        self.photos_count = [dictionary[@"photos_count"] integerValue];
        for (NSDictionary *dict in dictionary[@"trips"]) {
            PersonalModel *model = [[PersonalModel alloc]init];
//            if (dict[@"trips"][@"password"]) {
                [model setValuesForKeysWithDictionary:dict];
                [self.allDataArray addObject:model];
//            }
            
        }
        

        self.bLabel.text = [NSString stringWithFormat:@"%ld",self.trips_count];
        if (self.gender == 0) {
            self.senderImageView.image = [UIImage imageNamed:@"iconfont-weibiaoti2xingbie"];
        }else
        {
            self.senderImageView.image = [UIImage imageNamed:@"iconfont-xingbienannew-3"];
        }

        [self.aTableView reloadData];
        [self.refreshFooter endRefreshing];

        // "喜欢"解析
       
        [self.aTableView reloadData];
        
        

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    self.bView = [[UIView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width, 0, [UIScreen mainScreen].bounds.size.width - 10, self.view.frame.size.height -  CGRectGetMaxY(self.segmentCon.frame))];
    [self.aScrollView addSubview:self.bView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.aCollctionView = [[UICollectionView alloc]initWithFrame:self.bView.bounds collectionViewLayout:flowLayout];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    [self.bView addSubview:self.aCollctionView];
    
    
    self.aCollctionView.dataSource = self;
    self.aCollctionView.delegate = self;
    

    self.aCollctionView.backgroundColor = [UIColor whiteColor];
    [self.aCollctionView registerClass:[LCCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    
    

}

- (void)handleDataForPicWithPage:(NSInteger)page{
    [[CDHttpHelper defaultCDHttpHelper]get:[NSString stringWithFormat:@"https://chanyouji.com/api/users/likes/%@.json?per_page=18&page=%ld",self.model.user[@"id"],page] params:nil success:^(id responseObj) {
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        [self.allPicArray addObjectsFromArray:array];
        [self.aCollctionView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)updateData
{
    // 页面上方,下拉刷新
    self.aCollctionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.allDataArray removeAllObjects];
            [self handleDataForPicWithPage:self.totalPicPage];
            [self.aCollctionView.mj_header endRefreshing];
        });
    }];
    
    // 页面下方,上拉刷新
    self.aCollctionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.totalPicPage += 1;
        [self handleDataForPicWithPage:self.totalPicPage];
        
        [self.aCollctionView reloadData];
        [self.aCollctionView.mj_footer endRefreshing];
    }];
     
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.allPicArray.count;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LCCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    
    [cell.aImageVeiw sd_setImageWithURL:[NSURL URLWithString:self.allPicArray[indexPath.row][@"photo_url"]]];
    
    

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    return CGSizeMake([UIScreen mainScreen].bounds.size.width / 3 - 15, [UIScreen mainScreen].bounds.size.width / 3 - 5 );
}

-(void)pushacTion
{
    if (self.segmentCon.selectedSegmentIndex == 0) {
        self.aScrollView.contentOffset = CGPointMake(0, 0);
    }else{
        self.aScrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width, 0);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.aScrollView.contentOffset.x == 0) {
        self.segmentCon.selectedSegmentIndex = 0;
    }else{
        self.segmentCon.selectedSegmentIndex = 1;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 3;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 200;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allDataArray.count;
}


    
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *ID = @"cell";
    LCImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell ==nil) {
        cell = [[LCImageViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];
       
    }
    
    
    PersonalModel *model = self.allDataArray[indexPath.row];

    cell.aLabel.text = model.name;
    cell.bBlabel.text = [NSString stringWithFormat:@"%@ / %ld天",model.start_date,model.days];
    [cell.xiangqingImageView sd_setImageWithURL:[NSURL URLWithString:model.front_cover_photo_url]];
    
    return cell;
}

@end
